package demo.IOInputOutput;

import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

/**
 * @Auther: hjy(lc))
 * @Date: 2022/8/12-08-12-9:23
 * @Description：demo.IOInputOutput     管道流
 */
public class pipeLiu {
    public static void main(String[] args) {
        //声明并创建流
        PipedInputStream in = new PipedInputStream();
        PipedOutputStream out = new PipedOutputStream();
        //管道（读写线程）需要提前建立连接       //输入连接输出   或输出连接输入
        try {
            in.connect(out);
            //启动线程
            //写线程
            WriteThread write = new WriteThread(out);
            write.start();

            Thread.sleep(100);
            //读线程
            ReadThread read = new ReadThread(in);
            read.start();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
        //关闭流   线程中关
    }
}
class WriteThread extends Thread{
    private PipedOutputStream out;

    public WriteThread(PipedOutputStream out) {
        this.out = out;
    }

    @Override
    public void run() {
        byte[] temp = "abcdefg".getBytes();
        //temp 缓冲数组，为了一次性写出数据，提升效率
        try {
            out.write(temp);
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(out != null){
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
class ReadThread extends Thread{
    private PipedInputStream in;

    public ReadThread(PipedInputStream in) {
        this.in = in;
    }

    @Override
    public void run() {
        try{
            byte[] temp = new byte[1024];
            int len = -1;
            while ((len = in.read(temp)) != -1){
                System.out.write(temp,0,len);    //打印字符
                System.out.flush();
            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
